// Copyright (c) Lawrence Livermore National Security, LLC and other VisIt
// Project developers.  See the top-level LICENSE file for dates and other
// details.  No copyright assignment is required to contribute to VisIt.

// ************************************************************************* //
//                              avtPLYWriter.C                             //
// ************************************************************************* //

#include <avtPLYWriter.h>

#include <vector>
#include <vtkAppendPolyData.h>
#include <vtkCharArray.h>
#include <vtkTriangleFilter.h>
#include <vtkGeometryFilter.h>
#include <vtkPolyDataReader.h>
#include <vtkPolyDataWriter.h>
#include <vtkPointData.h>

#include <vtkScalarsToColors.h>
#include <vtkColorTransferFunction.h>
#include <avtColorTables.h>
#include <ColorTableAttributes.h>
#include <ColorControlPointList.h>
#include <ColorControlPoint.h>

#include <vtkPolyData.h>
#include <vtkPLYWriter.h>
#include <avtDatabaseMetaData.h>
#include <DBOptionsAttributes.h>
#include <DebugStream.h>
#include <avtParallel.h>
#ifdef PARALLEL
  #include <mpi.h>
#endif

using     std::string;
using     std::vector;


// ****************************************************************************
//  Method: avtPLYWriter constructor
//
//  Programmer: pugmire -- generated by xml2avt
//  Creation:   Tue Apr 16 08:57:58 PDT 2013
//
// ****************************************************************************

avtPLYWriter::avtPLYWriter(const DBOptionsAttributes *atts)
{
    doBinary = atts->GetBool("Binary format");
    doColor = atts->GetBool("Output colors");
    colorTable = atts->GetString("Color table");
    colorTableMin = atts->GetDouble("Color table min");
    colorTableMax = atts->GetDouble("Color table max");
}

// ****************************************************************************
//  Method: avtPLYWriter::OpenFile
//
//  Purpose:
//      Does no actual work.  Just records the stem name for the files.
//
//  Programmer: pugmire -- generated by xml2avt
//  Creation:   Tue Apr 16 08:57:58 PDT 2013
//
// ****************************************************************************

void
avtPLYWriter::OpenFile(const string &stemname, int numblocks)
{
    stem = stemname;
}


// ****************************************************************************
//  Method: avtPLYWriter::WriteHeaders
//
//  Purpose:
//      Writes out a VisIt file to tie the PLY files together.
//
//  Programmer: pugmire -- generated by xml2avt
//  Creation:   Tue Apr 16 08:57:58 PDT 2013
//
// ****************************************************************************

void
avtPLYWriter::WriteHeaders(const avtDatabaseMetaData *md,
                           const vector<string> &scalars,
                           const vector<string> &vectors,
                           const vector<string> &materials)
{
    // WRITE OUT HEADER INFO
}


// ****************************************************************************
//  Method: avtPLYWriter::WriteChunk
//
//  Purpose:
//      This writes out one chunk of an avtDataset.
//
//  Programmer: pugmire -- generated by xml2avt
//  Creation:   Tue Apr 16 08:57:58 PDT 2013
//
//  Modifications:
//    Brad Whitlock, Tue Sep  8 17:28:35 PDT 2015
//    Rely on base class to combine data.
//
// ****************************************************************************

void
avtPLYWriter::WriteChunk(vtkDataSet *ds, int chunk)
{
    if (ds->GetNumberOfCells() == 0)
    {
        debug4 << "avtPLYWriter::WriteChunk: No data to write" << endl;
        return;
    }

    std::string filename;
    if(writeContext.GroupSize() > 1)
    {
        char ext[20];
        snprintf(ext, 20, ".%d.ply", writeContext.GroupRank());
        filename = stem + ext;
    }
    else
        filename = stem + ".ply";


    vtkPLYWriter *writer = vtkPLYWriter::New();
    writer->SetFileName(filename.c_str());
    if(doBinary)
        writer->SetFileTypeToBinary();
    else
        writer->SetFileTypeToASCII();

    writer->SetInputData(ds);

    if (doColor && ds->GetPointData()->GetScalars())
    {
        vtkScalarsToColors *lut = GetColorTable();
        if (lut)
        {
            writer->SetArrayName(ds->GetPointData()->GetScalars()->GetName());
            writer->SetLookupTable(lut);
        }
    }
    
    writer->Update();
//    writer->Write();
    writer->Delete();
}

// ****************************************************************************
//  Method: avtPLYWriter::CloseFile
//
//  Purpose:
//      Closes the file.  This does nothing in this case.
//
//  Programmer: pugmire -- generated by xml2avt
//  Creation:   Tue Apr 16 08:57:58 PDT 2013
//
//  Modifications:
//
// ****************************************************************************

void
avtPLYWriter::CloseFile(void)
{
}

// ****************************************************************************
// Method: avtPLYWriter::CreateTrianglePolyData
//
// Purpose:
//   Tell VisIt's export that we'll want triangles.
//
// Returns:    True
//
// Programmer: Brad Whitlock
// Creation:   Tue Sep  8 17:00:23 PDT 2015
//
// Modifications:
//
// ****************************************************************************

bool
avtPLYWriter::CreateTrianglePolyData() const
{
    return true;
}

// ****************************************************************************
//  Method: avtTecplotWriter::GetCombineMode
//
//  Purpose:
//     Provides a hint to the export mechanism to tell it how to combine data.
//
//  Note: We combine geometry because PLY tools will want 1 file.
//
//  Programmer: Brad Whitlock
//  Creation:   Tue Sep  8 15:36:45 PDT 2015
//
// ****************************************************************************

avtDatabaseWriter::CombineMode
avtPLYWriter::GetCombineMode(const std::string &) const
{
    return CombineAll;
}

//****************************************************************************
// Method:  avtPLYWriter::GetColorTable()
//
// Purpose:
//   Create color table
//
//
// Programmer:  Dave Pugmire
// Creation:    April 26, 2013
//
// Modifications:
//   Justin Privitera, Mon Aug 21 15:54:50 PDT 2023
//   Changed ColorTableAttributes `names` to `colorTableNames`.
// 
//   Justin Privitera, Fri Nov  3 15:25:32 PDT 2023
//   Uses color table utility methods to improve performance.
//
//****************************************************************************

vtkScalarsToColors *
avtPLYWriter::GetColorTable()
{
    const ColorTableAttributes *colorTables = avtColorTables::Instance()->GetColorTables();
    const ColorControlPointList *table = colorTables->GetColorControlPoints(colorTable);
    if (table)
    {
        vtkColorTransferFunction *lut = vtkColorTransferFunction::New();

        double *vals = new double[3*table->GetNumControlPoints()];
        for (int i=0; i<table->GetNumControlPoints(); i++)
        {
            const ColorControlPoint &pt = table->GetControlPoints(i);
            vals[i*3 + 0] = pt.GetColors()[0]/255.0;
            vals[i*3 + 1] = pt.GetColors()[1]/255.0;
            vals[i*3 + 2] = pt.GetColors()[2]/255.0;
        }
        
        lut->BuildFunctionFromTable(colorTableMin, colorTableMax, table->GetNumControlPoints(), vals);
        delete [] vals;

        return lut;
    }
    return NULL;
}
